(function (window, undefined) {
    function TaskStatus() {
        this.name = "xv_status";
    }

    TaskStatus.prototype = {
        init: function () {
            const xv_status = localStorage.getItem(this.name);
            if (xv_status === "0" || xv_status === "1") {

            } else {
                this.completed();
            }
        },
        isdoing: function () {
            return localStorage.getItem(this.name) === "1";
        },
        doing: function () {
            localStorage.setItem(this.name, "1");
        },
        completed: function () {
            localStorage.setItem(this.name, "0");
        }
    }
    const _taskstatus = new TaskStatus();
    _taskstatus.init();

    function MPage() {
        this.key = "sid0090081";
        this.name = "";
        this.length = 0;
        this.success = 0;
    }

    MPage.prototype = {
        init: function () {
            var mvparam = {x: 0, Y: 0, screenX: 0, screenY: 0, bgc: null}
            var node = document.createElement("div");
            // node.innerHTML="<div id='sid0090081'></div>";
            node.id = this.key;
            node.draggable = true;
            node.style = "position:fixed;left:0;font-size:10px;top:0;z-index:9999;color:#fff;background-color:#333;width:200px;height:300px;"
            var phtml = [];
            phtml.push("<a class='name'></a>");
            phtml.push("<br /><a id='" + this.key + "btn'>start</a>");
            phtml.push("<span id='" + this.key + "id'>0</span>");
            phtml.push("<span id='" + this.key + "msg'>空</span>");
            phtml.push("<span id='" + this.key + "time'>999s</span>");
            phtml.push("<textarea id='txtdata' row=5 placeholder='多个请用换行或者,分割'></textarea>");
            phtml.push("<br /><span id='btnexportjson' style='display:none'>导出json</span>");
            phtml.push("<span id='btnexporttxt' style='display:none'>导出text</span> ");
            phtml.push("<br /><br /><br />   <span id='btnclear' style=''>清空数据</span>");
            node.innerHTML = "<p>" + phtml.join("|") + "</p>";
            node.ondragstart = function (ev) {
                ev.dataTransfer.effectAllowed = "copyMove";
                // mvparam.bgc=document.body.style.backgroundColor;
                // document.body.style.backgroundColor="#999999";
                mvparam.x = parseInt(ev.currentTarget.style.left.replace("px", ""), 0);
                mvparam.y = parseInt(ev.currentTarget.style.top.replace("px", ""), 0);
                mvparam.screenX = ev.screenX;
                mvparam.screenY = ev.screenY;
            };
            document.body.append(node);
            document.body.ondragover = function (ev) {
                ev.preventDefault();
            }
            document.body.ondrop = function (ev) {
                node.style.left = mvparam.x + (ev.screenX - mvparam.screenX) + "px";
                node.style.top = mvparam.y + (ev.screenY - mvparam.screenY) + "px";
            }
         document.getElementById("btnexportjson").addEventListener("click",function (){
             var strdblist = localStorage.getItem(domainkeys);
             saveShareContent(strdblist,"domains.json");
         },false);
            document.getElementById("btnexporttxt").addEventListener("click",function (){
                var strdblist = localStorage.getItem(domainkeys);
                var jsondata=JSON.parse(strdblist);
                var list=[];
                for (const a of jsondata){
                    list.push(a.key+";"+a.name+";"+a.time+";"+a.status);
                }
                saveShareContent(list.join("\n"),"domains.text");
            },false);
            document.getElementById("btnclear").addEventListener("click",function (){
                localStorage.removeItem(domainkeys);
                window.location.reload();
            },false);
        },
        bindbtn: function (obj) {
            var btn = document.getElementById(this.key + "btn");
            btn.addEventListener('click', showMsg, false); //鼠标单击的时候调用showMes这个函数
            function showMsg() {
                if (_taskstatus.isdoing()) {
                    btn.innerHTML = "start";
                    _taskstatus.completed();
                } else {
                    btn.innerHTML = "doing";
                    _taskstatus.doing();
                    obj.start();
                }
            }
        },
        setname: function (name, obj) {
            this.bindbtn(obj);
            document.querySelector("#" + this.key + " .name").innerHTML = name;
            if (_taskstatus.isdoing() === false) {
                return;
            } else {
                document.getElementById(this.key + "btn").innerHTML = "doing";
                obj.start();
            }
        },
        setId: function (id) {
            document.getElementById(this.key + "id").innerHTML = id;
        },
        msg: function (msg) {
            document.getElementById(this.key + "msg").innerHTML = msg;
        },
        timeout: function (t, url, callback) {
            if (t > 0) {
                this.showtimeout(t);
            }
            if (url) {
                setTimeout(function () {
                    // console.log(url);
                    if (_taskstatus.isdoing() === false) {
                        return;
                    }
                    window.location.href = url;
                }, t);
            }
            if (typeof (callback) === "function") {
                setTimeout(function () {
                    callback();
                }, t);
            }
        },
        showtimeout: function (t) {
            var start = new Date().getTime();
            var self = this;

            function tt() {
                var itval = new Date().getTime() - start;
                // console.log(itval,t);
                if (t - itval <= 0) {
                    document.getElementById(self.key + "time").innerHTML = '0s';
                    cancelAnimationFrame(tt);
                    return false;
                }
                document.getElementById(self.key + "time").innerHTML = parseInt((t - itval) / 1000, 10) + 's';
                requestAnimationFrame(tt);
            }

            tt();
        }
    };

    const _page = new MPage();
    _page.init();

    function Tools() {
        this.IsRun = false;
    }

    Tools.prototype = {
        getItem: function (key) {
            var tmpcpid = localStorage.getItem(key);
            if (tmpcpid && tmpcpid > 0) {
                return parseInt(tmpcpid, 10);
            }
            return 0;
        },
        fullPath: function (url) {
            var a = document.createElement('A');
            a.href = url;
            url = a.href;
            return url;
        },
        getFirstFloat: function (str) {
            for (var i = 0; i < str.length; i++) {
                var c = str.charCodeAt(i);
                if (c == 46 || (c >= 48 && c <= 57)) {
                    continue;
                } else {
                    if (i > 0) {
                        return str.substr(0, i);
                    }
                    return 0;
                }
            }
            return 0;
        },
        getParams: function (key) {
            var urlsearch = new URL(window.location.href);
            return urlsearch.searchParams.get(key);
        },
        getNumber: function (str) {
            var start = -1;
            for (var i = 0; i < str.length; i++) {
                var c = str.charCodeAt(i);
                if (start == -1 && c >= 48 && c <= 57) {
                    start = i;
                }
                if (start >= 0 && (c < 48 || c > 57)) {
                    return str.substr(start, i - start)
                }
            }
            if (start >= 0) {
                return str.substr(start)
            }
            return "";
        },
        getFirstNumber: function (str) {
            for (var i = 0; i < str.length; i++) {
                var c = str.charCodeAt(i);
                if (c < 48 || c > 57) {
                    return str.substr(0, i);
                }
            }
            return str;
        },
        objectExistsKey: function (obj, key) {
            var exists = false;
            for (a in obj) {
                if (a === key) {
                    exists = true;
                    break;
                }
            }
            return exists;
        },
        nodeExists: function (name) {
            if (document.querySelectorAll(name).length > 0) {
                return true;
            }
            return false;
        },
        alllink: function (filter) {
            var list = document.querySelectorAll("a");
            var listurl = [];
            for (var i = 0; i < list.length; i++) {
                var turl = list[i].getAttribute("href");
                if (turl) {
                    var qurl = _tool.fullPath(turl);
                    if (filter) {
                        if (qurl.indexOf(filter) >= 0) {
                            listurl.push(qurl);
                        }
                    } else {
                        listurl.push(qurl);
                    }
                }
            }
            return listurl;
        }
    };

    var _tool = new Tools();
    const domainkeys="domainkeys";
    function loadaDomainsStart() {
        console.log("loadaDomainsStart");
        if (document.querySelector("#txtdata").textLength) {
            var datalist = [];
            var rows = document.querySelector("#txtdata").value.split(",");
            for (const x in rows) {
                ys = rows[x].split("\n");
                for (const y in ys) {
                    if (ys[y]) {
                        // console.log(y);
                        datalist.push({key: ys[y], name: null, time: null, status: null});
                    }
                }
            }
            if (datalist.length > 0) {
                localStorage.setItem(domainkeys, JSON.stringify(datalist));
            }
        }
        ADomainsSetid();
        setInputValue();
        // startquery("oracle");// fail
        //e10smef00
    }
    function  checknext(){
        console.log("checknext");
        var strdblist = localStorage.getItem(domainkeys);
        var jsonlist = JSON.parse(strdblist);
        for (const x in jsonlist) {
            if(jsonlist[x].status==null){
                _page.timeout(500, window.location.href.substr(0, 31) + jsonlist[x].key);
                return false;
            }
        }
        if(jsonlist&&jsonlist.length>0) {
            document.querySelector("#btnexportjson").style.display = "inline";
            document.querySelector("#btnexporttxt").style.display = "inline";
        }
    }
    function  setInputValue(){
        console.log("setInputValue");
        var key=window.location.href.substr(31);
        var strdblist = localStorage.getItem(domainkeys);
        var jsonlist = JSON.parse(strdblist);
        var extkey=false;
        for (const x in jsonlist) {
            if (jsonlist[x].key == key) {
                extkey=true;
                setStatusValue(jsonlist, parseInt(x,10));
            }
        }
        if (extkey==false){
            checknext();
        }
        // document.querySelector(".e1736otp5").innerText ："status"
        // document.querySelector(".e1736otp3").innerText ："oracle.eth"
        // document.querySelector(".erk1q1g0").innerText ："Expires 2027.10.16 at 19:48 (UTC+08:00)"
    }

    function saveShareContent (content, fileName) {
        let downLink = document.createElement('a')
        downLink.download = fileName
        //字符内容转换为blod地址
        let blob = new Blob([content])
        downLink.href = URL.createObjectURL(blob)
        // 链接插入到页面
        document.body.appendChild(downLink)
        downLink.click()
        // 移除下载链接
        document.body.removeChild(downLink)
    }

    function  setStatusValue(jsonlist,x){
        if (document.querySelector(".e1736otp5")&&document.querySelector(".e1736otp5").innerText){
            jsonlist[x].status=document.querySelector(".e1736otp5").innerText;
            jsonlist[x].name=document.querySelector(".e1736otp3")?.innerText;
            jsonlist[x].time=document.querySelector(".erk1q1g0")?.innerText;
            localStorage.setItem(domainkeys,JSON.stringify(jsonlist));
            ADomainsSetid();
            checknext();
        }else {
            setTimeout(function () {
                setStatusValue(jsonlist,x);
            }, 1000)
        }
    }
    function  startquery(key) {
        if (document.querySelector(".e10smef00 input")) {
            // document.querySelector(".e10smef00 input").focus();
            for(var i=0;i<key.length;i++){
                // console.log(key.charCodeAt(i));
                document.querySelector(".e10smef00 input").focus();
                // document.body.pressKey(key.charCodeAt(i));
                document.querySelector(".e10smef00 input").pressKey(key.charCodeAt(i));
            }
            // console.log("ssssssv009");


            if(document.querySelector(".e10smef00 button").hasAttribute("disabled")){
                document.querySelector(".e10smef00 button").removeAttribute("disabled");
            }
            document.querySelector(".e10smef00 submit").click();
        } else {
            setTimeout(function () {
                startquery(key);
            }, 1000)
        }
    }
    function ADomainsSetid() {
        var strdblist = localStorage.getItem(domainkeys);
        var jsonlist = JSON.parse(strdblist);
        if (jsonlist == null) {
            _page.setId("0/0");
            return;
        }
        var oknum = 0;
        for (const x of jsonlist) {
            if (x.time && x.time.length > 0) {
                oknum++;
            }
        }
        _page.setId( oknum+"/"+jsonlist.length);
    }


    function myinit() {
        if (window.location.href.indexOf("https://app.ens.domains") >=0) {
            var appensdomains = function () {
            }
            appensdomains.prototype = {
                start: function () {
                    loadaDomainsStart();
                }
            }
            _page.setname("domains", new appensdomains());
        }
        console.log(window.location.href);
    }
    myinit();
})(window);
